// pages/order/order.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // countdown:'09分23秒',
    timer: null,
    currentIndex: '-1', // 默认选中第一个
    orders:[],
    ordersFilter:[],
    phone:wx.getStorageSync('phone'),
    showAuthPopup: false,
    
  },
  gotoOrderDetail:function(e){
    wx.navigateTo({
      url: '/pages/orderDetail/orderDetail?id='+e.currentTarget.dataset.id+'&type='+e.currentTarget.dataset.type
    })
  },
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentIndex: index
    });
    this.filteredOrders();
  },
  copyBtn: function (e) {
    console.log(1210,e.currentTarget.dataset.id);
    //当前索引
    wx.setClipboardData({
      //准备复制的数据内容
      data: e.currentTarget.dataset.id,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    });
  },
  //过滤订单
  filteredOrders(){
    if(this.data.currentIndex!='-1'){
      let filteredItems;
      if(this.data.currentIndex==2){
        filteredItems = this.data.orders.filter(item => item.state == 2 || item.state == 3);
      }else{
        filteredItems = this.data.orders.filter(item => item.state == this.data.currentIndex);
      }
      this.setData({
        ordersFilter:filteredItems,
      });
    }else{
      this.setData({
        ordersFilter:this.data.orders,
      });
    }
    this.startGlobalTimer(); // 启动全局定时器
    
  },
//获取订单
getOrder:function(){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/getNewOrder', 
    method: 'POST',
    data: {
      phone:_this.data.phone
    },
    success: function(res) {
      console.log(123,res.data.data);
      res.data.data.forEach(function(item) {
        item.goodsJson = JSON.parse(item.goodsJson);
        if(item.state==0){
          const createTime = new Date(item.createTime).getTime();
          item.endTime=createTime + 600000,
          item.countdown=_this.calculateCountdown(createTime + 600000)
        }
        if(item.order_type==1 && item.state==2){
          item.state=3
        }
      });
      console.log(898989,res.data.data);
      _this.setData({
        orders:res.data.data
      })
      // console.log(3434,_this.data.orders[0].goodsJson);
      _this.filteredOrders();
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},
// 启动全局定时器（每秒触发一次）
startGlobalTimer() {
  let _this=this;
  this.data.timer = setInterval(() => {
    const now = Date.now();
    const updatedOrders = this.data.ordersFilter.map(order => {
      if (order.state === 0 && order.endTime) {
        const remaining = order.endTime - now;
        if (remaining <= 0) {
          // 倒计时结束，更新状态为 4
          _this.updateNewOrder(order.orderId,4)
          _this.updateInventory(order.goodsJson);
          _this.backCoupon(order);
          _this.getOrder()
          return { ...order, state: 4, countdown: "已过期" };
        } else {
          // 更新倒计时显示
          return {
            ...order,
            countdown: this.calculateCountdown(order.endTime)
          };
        }
      }
      return order;
    });
    this.setData({ ordersFilter: updatedOrders });
  }, 1000);
},

// 计算剩余时间并格式化为 "MM:SS"
calculateCountdown(endTime) {
  const remaining = endTime - Date.now();
  const minutes = Math.floor(remaining / 60000);
  const seconds = Math.floor((remaining % 60000) / 1000);
  const format = num => num.toString().padStart(2, '0');
  return `${format(minutes)}:${format(seconds)}`;
},
//取消订单
quitList : function (e) {
  let _this=this;
  wx.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: function (sm) {
      if (sm.confirm) {
        _this.updateNewOrder(e.currentTarget.dataset.id,4)
        let order=_this.data.orders.find(item => item.orderId === e.currentTarget.dataset.id);
        _this.updateInventory(order.goodsJson);
        _this.backCoupon(order);
      } 
    }
  })
},
//删除订单
delList : function (e) {
  let _this=this;
  wx.showModal({
    title: '提示',
    content: '确定要删除订单吗？',
    success: function (sm) {
      if (sm.confirm) {
        _this.updateNewOrder(e.currentTarget.dataset.id,9)
      } 
    }
  })
  
},
//确认收货
okList : function (e) {
  let _this=this;
  wx.showModal({
    title: '提示',
    content: '点击确认按钮，将确认收货',
    success: function (sm) {
      if (sm.confirm) {
        _this.updateNewOrder(e.currentTarget.dataset.id,3)
      } 
    }
  })
  
},
//售后
service : function (e) {

},
//处理库存
updateInventory(goodsList){
  goodsList.forEach(good => {
    this.setInventory(good.productId, good.buyNum);
  });
},
//修改库存
setInventory(id,buyNum){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/quitInventory', 
    method: 'POST',
    data: {
      id:id,
      buyNum:buyNum,
    },
    success: function(res) {
      console.log("库存处理成功");
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},

//修改订单状态
updateNewOrder: function (id,state) {
  console.log(id,state)
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/updateNewOrder', 
    method: 'POST',
    data: {
      orderId:id,
      state:state,
    },
    success: function(res) {
      console.log(325)
      _this.getOrder();
    },
    fail: function(err) {
    },
    complete: function() {}
  });
},

//支付
payOrder: function(event) {
  let openid=wx.getStorageSync('openid')
  let phone=wx.getStorageSync('phone');
  
  let orderId=event.currentTarget.dataset.id
  let text=orderId;
  let total_fee=event.currentTarget.dataset.money
  let _this=this
  wx.request({
    url: app.globalData.onlineUrl+'/wxpay',
    data: {
      Goods:{
        text:text,
        total_fee: total_fee*100,
      },
      openid: openid,
      orderId:orderId,
      phone:phone,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
      console.log(1,res.data.data.data)
      let result=res.data.data.data
      wx.requestPayment({
        timeStamp: result.timeStamp,
        nonceStr: result.nonceStr,
        package: result.package,
        signType: result.signType,
        paySign: result.paySign,
        success: res => {
          _this.insertCoupon(orderId)
          _this.sendVipGift(orderId);
          _this.getOrder()
        },
        fail: res => {
          console.log(3,res)
        }
      })
    },
  })
},
//送会员礼包
sendVipGift:async function (orderId) {
  let order=this.data.orders.find(item => item.orderId === orderId);
  console.log(1,order);
  let vip= order.goodsJson.filter(item => item['productId'] == 114 || item['productId'] == 115 || item['productId'] == 116 || item['productId'] == 117)
  let _this=this;
  console.log(8866,vip);
  if (vip.length > 0) {
    for (const obj of vip) {
      console.log(888, obj);
      // 增加购买数量循环
      for (let a = 1; a <= obj.buyNum; a++) {
        // 等待当前VIP权益发送完成后再处理下一个
        await _this.sendVip(obj.productId);
      }
    }
  }
},
//给用户送会员权益
sendVip: function (id) {
  return new Promise((resolve, reject) => {
    let vipType = 0;
    switch(Number(id)) {
      case 114: vipType = 1; break;
      case 115: vipType = 2; break;
      case 116: vipType = 3; break;
      case 117: vipType = 4; break;
      default: 
        console.log('Invalid VIP product id:', id);
        reject(new Error('无效的会员产品ID'));
        return;
    }
    
    const phone = wx.getStorageSync('phone');
    wx.request({
      url: app.globalData.onlineUrl + '/vip/buy',
      data: {
        phone: phone,
        vipType: vipType,
      },
      header: {'content-type': 'application/json'},
      method: "POST",
      dataType: "json",
      success: res => {
        console.log('VIP发送成功:', res);
        resolve(res);
      },
      fail: err => {
        console.error('VIP发送失败:', err); // 添加错误日志
        reject(err); // 仅在失败时reject
      },
      // 移除complete回调，避免状态冲突
    });
  });
},
backCoupon(order){
  console.log(1,order);
  if(order.couponId){
    let _this=this;
    wx.request({
      url: app.globalData.onlineUrl+'/backCoupon',
      data: {
        phone:wx.getStorageSync('phone'),
        id:order.couponId,
      },
      header:{'content-type': 'application/json'},
      method:"POST",
      dataType:"json",
      success: res => {
      }
    })
  }
},
//塞券
insertCoupon: function (orderId) {
  let order=this.data.orders.find(item => item.orderId === orderId);
  console.log(1,order);
  let coupons=[];
  if(order){
    coupons= order.goodsJson.filter(item => item.iscoupon == 1)
  }
  console.log(2,coupons);
  let _this=this;
  if(coupons.length!=0){
    coupons.forEach(function(obj) {
      console.log(3,obj)
      for(let a = 1; a<=obj.buyNum;a++){
        _this.sendQuan(obj.productId);
      }
    });
  }
},
//给用户送券
sendQuan(couponId){
  let _this=this;
  wx.request({
    url: app.globalData.onlineUrl+'/addCouponForUser',
    data: {
      phone:wx.getStorageSync('phone'),
      couponId:couponId,
    },
    header:{'content-type': 'application/json'},
    method:"POST",
    dataType:"json",
    success: res => {
    }
  })
},
//退款
payOutOrder: function (event) {
  let _this=this
  wx.showModal({
    title: '提示',
    content: '你正在进行退款操作，是否确认？',
    success: function (sm) {
      if (sm.confirm) {
        let orderId=event.currentTarget.dataset.type
        let money=event.currentTarget.dataset.money
        console.log("orderId",orderId);
        //修改订单状态
        wx.request({
          url: app.globalData.onlineUrl+'/wx_refund',
          data: {
            out_trade_no:orderId,
            money:money
          },
          header:{'content-type': 'application/json'},
          method:"POST",
          dataType:"json",
          success: res => {
            _this.updateNewOrder(orderId,8)
          }
        })
      } 
    }
  })
  
},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(!wx.getStorageSync('phone')){
      this.setData({ showAuthPopup: true });
    }
    app.getBuyCarNum()
    this.getTabBar().setData({
      PageCur: 'order'
    })
    this.setData({
      phone:wx.getStorageSync('phone'),
      uid:wx.getStorageSync('uid')
    })
    this.getOrder();
    
  },
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const { encryptedData, iv } = e.detail;
      wx.login({
        success: res => {
          if (res.code) {
            // 发送 res.code 到后台换取 openid, session_key, unionid
            wx.request({
              url: app.globalData.onlineUrl+"/getUserPhone", // 替换为你的服务器地址
              header:{'content-type': 'application/json'},
              method: 'POST',
              data: {
                code: res.code,
                encryptedData:encryptedData,
                iv:iv,
              },
              success: (response) => {
                console.log(10086,response.data.data.phoneNumber);
                // 存储用户信息
                wx.setStorageSync('phone', response.data.data.phoneNumber);
                wx.setStorageSync('openid', response.data.data.openId);
                this.setUser();
                this.setData(
                  {
                    phone:wx.getStorageSync('phone'),
                    showAuthPopup:false
                  }
                )
                this.getOrder();
              }
            });
          } else {
            console.log('登录失败！' + res.errMsg);
          }
        }
      });
    } else {
      // 用户拒绝授权时的处理（根据合规要求，建议允许用户取消）
      wx.showToast({ 
        title: '需要授权手机号才能使用完整服务', 
        icon: 'none',
        duration: 2000
      });
    }
  },
  setUser:function(){
    let _this=this;
    wx.request({
      url:app.globalData.onlineUrl+"/setUser",
      header:{'content-type': 'application/json'},
      method:"POST",
      data:{
        phone:wx.getStorageSync('phone'),
        openId:wx.getStorageSync('openid')
      },
      dataType:"json",
      complete:function(result) {
        console.log("用户信息更新成功");
      }
    })
  },
  onClosePopup() {
    this.setData({ showAuthPopup: false });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
/**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    console.log(12242);
    return {
      title: '来伊份零食会员权益',
      path: 'pages/index/index',
      imageUrl: '/images/share.png'
    }
  }
})